package cn.zr.aitool.fragments;

import android.content.Context;
import android.content.DialogInterface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.github.clans.fab.FloatingActionButton;
import com.github.clans.fab.FloatingActionMenu;

import java.util.Collections;
import java.util.List;

import cn.zr.aitool.R;
import cn.zr.aitool.bean.ContentBean;
import cn.zr.aitool.db.ContentManager;
import cn.zr.aitool.view.AlertDialogHelper;
import cn.zr.aitool.view.EidtDialog;
import cn.zr.aitool.view.SpacesItemDecoration;

/**
 * A fragment representing a list of Items.
 * <p/>
 * Activities containing this fragment MUST implement the {@link OnListFragmentInteractionListener}
 * interface.
 */
public class ItemFragment extends Fragment implements View.OnClickListener {
    private static final String TAG = "ItemFragment";
    private static final String FROM_ON_CTEATE = "create";

    private static final String ARG_INDEX = "index";
    private int mColumnCount;
    private OnListFragmentInteractionListener mListener;
    private FloatingActionMenu mFAmenu;
    private FloatingActionButton mBtnAdd;
    private FloatingActionButton mBtnEdit;
    private FloatingActionButton mBtnClear;
    private EidtDialog eidtDialog;
    private RecyclerView recyclerView;
    private ContentItemAdapter mAdapter;

    /**
     * Mandatory empty constructor for the fragment manager to instantiate the
     * fragment (e.g. upon screen orientation changes).
     */
    public ItemFragment() {
    }

    @SuppressWarnings("unused")
    public static ItemFragment newInstance(int columnCount) {
        ItemFragment fragment = new ItemFragment();
        Bundle args = new Bundle();
        args.putInt(ARG_INDEX, columnCount);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mColumnCount = getArguments().getInt(ARG_INDEX);
            Log.i(TAG, "onCreate mColumnCount:" + mColumnCount);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_item_list, container, false);
        recyclerView = view.findViewById(R.id.list);
        recyclerView.setLayoutManager(new StaggeredGridLayoutManager(2, RecyclerView.VERTICAL));
        SpacesItemDecoration decoration = new SpacesItemDecoration(4);
        recyclerView.addItemDecoration(decoration);
        mFAmenu = view.findViewById(R.id.menu_labels_right);
        mBtnAdd = view.findViewById(R.id.fbtn_add);
        mBtnEdit = view.findViewById(R.id.fbtn_edit);
        mBtnClear = view.findViewById(R.id.fbtn_clear);
        setFlBtnClickListener();
        ContentTask task =  new ContentTask();
        task.setType(FROM_ON_CTEATE);
        task.execute();
        return view;
    }

    private void setFlBtnClickListener() {
        mBtnAdd.setOnClickListener(this);
        mBtnEdit.setOnClickListener(this);
        mBtnClear.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        mFAmenu.close(true);
        switch (v.getId()) {
            case R.id.fbtn_add:
                eidtDialog = new EidtDialog(ItemFragment.this.getActivity(), mColumnCount);
                eidtDialog.setOnCommitListener(new EidtDialog.OnCommitListener() {
                    @Override
                    public void onCommit() {
                        new ContentTask().execute();
                    }
                });
                eidtDialog.show();
                break;
            case R.id.fbtn_edit:
                break;
            case R.id.fbtn_clear:
                showConfirmDialog();
                break;
            default:
                break;
        }
    }

    private void showConfirmDialog() {
        AlertDialogHelper.showDialog(ItemFragment.this.getActivity(), "清空所有数据?", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                ContentManager.getInstance().deleteContentPosition(mColumnCount);
                new ContentTask().execute();
            }
        });
    }

    private class ContentTask extends AsyncTask<String, Object, List<ContentBean>> {
        private String mType;
        public void setType(String type){
            this.mType=type;
        }

        @Override
        protected void onPreExecute() {
        }

        @Override
        protected List<ContentBean> doInBackground(String... params) {
            List<ContentBean> contents = ContentManager.getInstance().queryContentByPosition(mColumnCount);
            Collections.reverse(contents);
            return contents;
        }

        @Override
        protected void onPostExecute(List<ContentBean> result) {
            Log.i(TAG, "onPostExecute(Result result) result:" + result.size());
            if(TextUtils.equals(mType,FROM_ON_CTEATE)){
                bindData(result);
            }else{
                if (mAdapter == null) {
                    bindData(result);
                } else {
                    Log.i(TAG, "mAdapter is not NULL" );
                    mAdapter.setData(result);
                    mAdapter.notifyDataSetChanged();
                }
            }
        }
    }

    private void bindData(List<ContentBean> result){
        mAdapter = new ContentItemAdapter(result, new OnListFragmentInteractionListener() {
            @Override
            public void onListFragmentInteraction(ContentItemAdapter.ViewHolder holder) {
                mListener.onListFragmentInteraction(holder);
            }

            @Override
            public void onLongClick(ContentItemAdapter.ViewHolder holder) {
                showDeleteConfirmDialog(holder.mItem.id);
            }
        }, mColumnCount);
        recyclerView.setAdapter(mAdapter);
    }


    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof OnListFragmentInteractionListener) {
            mListener = (OnListFragmentInteractionListener) context;
        } else {
            throw new RuntimeException(context.toString()
                    + " must implement OnListFragmentInteractionListener");
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        Log.i(TAG, "onResume mColumnCount:" + mColumnCount);
    }

    @Override
    public void onStart() {
        super.onStart();
        Log.i(TAG, "onStart mColumnCount:" + mColumnCount);
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    public interface OnListFragmentInteractionListener {
        /**
         * 点击事件
         *
         * @param holder
         */
        void onListFragmentInteraction(ContentItemAdapter.ViewHolder holder);

        /**
         * 长按事件
         *
         * @param holder
         */
        void onLongClick(ContentItemAdapter.ViewHolder holder);

    }

    private void showDeleteConfirmDialog(final int index) {
        AlertDialogHelper.showDialog(ItemFragment.this.getActivity(), "删除数据?", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                ContentManager.getInstance().deleteById(index);
                new ContentTask().execute();
            }
        });
    }
}
